package net.yienyien.process.bpel.generator.controlFlow;

import java.util.HashMap;
import java.util.Map;

import javax.xml.namespace.QName;

import net.yienyien.process.bpel.generator.Production;

import org.eclipse.emf.ecore.xml.type.XMLTypePackage;
import org.eclipse.emf.ecore.xml.type.util.XMLTypeUtil;
import org.eclipse.xsd.XSDPackage;
import org.open.oasis.docs.wsbpel._2._0.process.abstract_.AbstractFactory;
import org.open.oasis.docs.wsbpel._2._0.process.abstract_.TActivity;
import org.open.oasis.docs.wsbpel._2._0.process.abstract_.TAssign;
import org.open.oasis.docs.wsbpel._2._0.process.abstract_.TCopy;
import org.open.oasis.docs.wsbpel._2._0.process.abstract_.TFrom;
import org.open.oasis.docs.wsbpel._2._0.process.abstract_.TTo;
import org.open.oasis.docs.wsbpel._2._0.process.abstract_.TVariable;

public class ControlExpressionHandler {
	
	private Map<String, TVariable> controlVariable;
	private Production production;
	
	public ControlExpressionHandler(Production production) {
		this.production=production;
		controlVariable=new HashMap<String, TVariable>();
	}
	
	public boolean isControlExpression(String stg) {
		return stg.contains("$");
	}
	
	public TActivity createControlExpression(String stg) {	
		if(stg.contains("=")) {
			return createAssignment(stg);
		} else {
			assert(false): "Unknow expression";
		}
		
		return null;
	}
	
	private TActivity createAssignment(String stg) {
		String[] parts=stg.split("=");
		assert(parts.length==2);
		
		TAssign assign=AbstractFactory.eINSTANCE.createTAssign();
		TCopy copy=AbstractFactory.eINSTANCE.createTCopy();
		
		assign.getCopy().add(copy);
		
		TFrom from=AbstractFactory.eINSTANCE.createTFrom();
		TTo to=AbstractFactory.eINSTANCE.createTTo();
		
		from.getAny().add(XMLTypePackage.eINSTANCE.getXMLTypeDocumentRoot_Text(), parts[1]);
		
		to.setVariable(assertVariable(parts[0].substring(1), null).getName());
		
		copy.setFrom(from);
		copy.setTo(to);
		
		return assign;
	}
	
	
	private TVariable assertVariable(String name, Object type) {
		TVariable var=controlVariable.get(name);
		if(var==null) {
			var= AbstractFactory.eINSTANCE.createTVariable();
			var.setName(name);
			QName qname=(QName) XMLTypeUtil.createQName("http://www.w3.org/2001/XMLSchema", "int", "");

			var.setType(qname);
			/* Initialization */
			TFrom from=AbstractFactory.eINSTANCE.createTFrom();
			from.getAny().add(XMLTypePackage.eINSTANCE.getXMLTypeDocumentRoot_Text(), "0");
			var.setFrom(from);
			
			controlVariable.put(name, var);
			production.getProcess().getVariables().getVariable().add(var);
			
		}
		return var;
	}
}
